<template>
  <div>
    <a-modal v-model:visible="visible" title="添加Banner" okText="提交" cancelText="取消" @ok="onSubmit">
      <a-form :label-col="labelCol" :wrapper-col="wrapperCol">
        <a-form-item label="图片描述" required>
          <a-input v-model:value="modelRef.alt" />
        </a-form-item>
        <a-form-item label="图片链接" required>
          <a-input v-model:value="modelRef.link" />
        </a-form-item>
        <a-form-item label="图片上传">
          <a-upload v-model:file-list="fileList" :before-upload="beforeUpload" :show-upload-list="false"
            @change="handleChange" class="avatar-uploader" list-type="picture-card" name="avatar"
            action="http://121.89.205.189:3000/admin/banner/add">
            <img v-if="imageUrl" :src="imageUrl" alt="avatar" />
            <div v-else>
              <loading-outlined v-if="loading"></loading-outlined>
              <plus-outlined v-else></plus-outlined>
              <div class="ant-upload-text">Upload</div>
            </div>
          </a-upload>
        </a-form-item>
        <!-- <a-form-item class="error-infos" :wrapper-col="{ span: 14, offset: 4 }" v-bind="errorInfos">
          <a-button type="primary" @click.prevent="onSubmit">提交</a-button>
          <a-button style="margin-left: 10px" @click="resetFields">重置</a-button>
        </a-form-item> -->
      </a-form>
    </a-modal>
  </div>
</template>
<script setup>
import { reactive, toRaw, computed, ref } from 'vue'
import { toArray } from 'lodash-es'
import { Form } from 'ant-design-vue'
import { PlusOutlined, LoadingOutlined } from '@ant-design/icons-vue';
import { message } from 'ant-design-vue'
import request from '@/utils/request'

const emit = defineEmits(['loadData'])

function getBase64(img, callback) {
  const reader = new FileReader();
  reader.addEventListener('load', () => callback(reader.result));
  reader.readAsDataURL(img);
}

const fileList = ref([])
const loading = ref(false)
const imageUrl = ref('')
const handleChange = info => {
  if (info.file.status === 'uploading') {
    loading.value = true;
    return;
  }
  if (info.file.status === 'done') {
    // Get this url from response in real world.
    getBase64(info.file.originFileObj, base64Url => {
      imageUrl.value = base64Url;
      loading.value = false;
    });
  }
  if (info.file.status === 'error') {
    loading.value = false;
    message.error('upload error');
  }
};
const beforeUpload = file => {
  const isJpgOrPng = file.type === 'image/jpeg' || file.type === 'image/png';
  if (!isJpgOrPng) {
    message.error('You can only upload JPG file!');
  }
  const isLt2M = file.size / 1024 / 1024 < 2;
  if (!isLt2M) {
    message.error('Image must smaller than 2MB!');
  }
  return isJpgOrPng && isLt2M
};


const useForm = Form.useForm

const labelCol = reactive({
  span: 8,
})

const wrapperCol = reactive({
  span: 14,
})

const modelRef = reactive({
  alt: '',
  link: '',
  img: '',
})

const rulesRef = reactive({
  alt: [{
    required: true,
    message: 'Please input alt',
  }],
  link: [{
    required: true,
    message: 'Please input link',
  }]
})

const {
  resetFields,
  validate,
  validateInfos,
  mergeValidateInfo,
} = useForm(modelRef, rulesRef)

const onSubmit = () => {
  validate().then(() => {
    if (imageUrl.value === '') {
      message.info('你还没有上传图片！');
    } else {
      request({
        url: '/banner/add',
        data: {
          ...modelRef,
          img: imageUrl.value
        },
        method: 'post'
      }).then((res) => {
        modelRef.alt = ''
        modelRef.link = ''
        imageUrl.value = ''
        visible.value = false
        emit('loadData')
      })
    }
  }).catch(err => {
    console.log('error', err);
  });
};
const errorInfos = computed(() => {
  return mergeValidateInfo(toArray(validateInfos));
})

const visible = ref(false)
const showModal = () => {
  visible.value = true
}
const handleOk = e => {
  visible.value = false
}

defineExpose({
  showModal
})
</script>